package com.icbc.ctpdemo.user.opstep;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.icbc.cte.base.TranFailException;
import com.icbc.cte.logging.Log;
import com.icbc.cte.logging.LogFactory;
import com.icbc.ctp.core.IContext;
import com.icbc.ctp.core.annotations.Input;
import com.icbc.ctp.core.annotations.Output;
import com.icbc.ctp.core.impl.OperationStep;

/**
 * TODO 类的描述：。
 * 
 * <pre>
 * 	判断当前新增/修改用户的角色列表中是否存在互斥角色
 * </pre>
 * 
 * <pre>
 * modify by kfzx-lvsx on 2014-4-26
 *    fix->1.
 *         2.
 * </pre>
 */
@Input(name = { "userInRoleList", "refAllRoleExclu" }, type = {
		"java:java.util.Map", "java:java.util.List" }, mustInput = { true, true }, isVariable = {
		true, true }, isArray = { false, false }, description = { "用户的角色列表",
		"所有互斥角色列表" })
@Output(name = "out_flag", type = "java:java.lang.String", isArray = false, description = "0：用户角色列表不互斥  -4：用户角色列表存在互斥角色")
public class RoleExclusionJudgementOpStep extends OperationStep {

	private Log ctpLog = LogFactory.getCtpLog(RoleExclusionJudgementOpStep.class);
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.icbc.ctp.core.impl.OperationStep#execute(com.icbc.ctp.core.IContext)
	 */
	@Override
	protected int execute(IContext arg0) throws TranFailException {
		List tmpUserInRoleList = (List<Object>) arg0.getValueAt("userInRoleList");
		List tmpRefAllRoleExclu = (List<Object>) arg0.getValueAt("refAllRoleExclu");
		Map<String, String> roleMap = new HashMap<String, String>();
		List<String> excluList = new ArrayList<String>();
		String out_flag = "0";
		String errMsg = "";
		
		try{
			if(null != tmpRefAllRoleExclu){
				List<String> userInRoleList = this.toList(tmpUserInRoleList);
				Map<String, String> refAllRoleExclu = this.exclusionToMap(tmpRefAllRoleExclu, roleMap);
				
				String thisRole = "";
				String nextRole = "";
				
				//在新增用户角色列表中，两两比较看是否互斥
				for(int i = 0; i<userInRoleList.size(); i++){
					boolean flag = false;
					thisRole = userInRoleList.get(i);
					for (int j = i + 1; j < userInRoleList.size(); j++) {
						nextRole = userInRoleList.get(j);
						flag = existExclusionRole(thisRole, nextRole, refAllRoleExclu);
						if(flag){
							excluList.add(roleMap.get(thisRole) + ", " + roleMap.get(nextRole));
						}
					}
				}
				
				if (excluList.size() > 0) {
					out_flag = "-4";
				}
				
				//out_flag不为0，存在互斥角色，抛出异常，使事务回滚，新增角色失败
				if (!"0".equals(out_flag)) {
					StringBuffer errMsgSB = new StringBuffer();
					
					for (String string : excluList) {
						errMsgSB.append("(");
						errMsgSB.append(string);
						errMsgSB.append("),");
					}
					setOutputValue(arg0, "out_flag", out_flag);
					errMsg = errMsgSB.toString().substring(0, errMsgSB.toString().length()-1);
					throw new Exception();
				}
			}
		}catch (Exception e) {
			ctpLog.error("password is invalid for the reason: " + errMsg);
			TranFailException ctee = new TranFailException("ROLE-EXCLUSION-ERR-000001", "RoleExclusionJudgementOpStep", "", new Object[] { errMsg });;
			arg0.setValueAt("opErrMsg", ctee.getLocalizedMessage());
			inException(arg0, ctee);
			return -1;
		}
		
		

		setOutputValue(arg0, "out_flag", out_flag);
		return 0;
	}
	
	//判断当前这两个角色是否互斥
	private boolean existExclusionRole(String thisRole, String nextRole,
			Map<String, String> refAllRoleExclu) {
		//要改
		for (String key : refAllRoleExclu.keySet()) {
			if(-1 != refAllRoleExclu.get(key).indexOf(thisRole) && -1 != refAllRoleExclu.get(key).indexOf(nextRole)){
				return true;
			}
		}
		return false;
	}

	private List<String> toList(List<Object> list){
		Map tmpMap = null;
		List<String> resultList = new ArrayList<String>();
		for (Object object : list) {
			if(object instanceof Map){
				tmpMap = (Map) object;
				resultList.add((String) tmpMap.get("id"));
			}
		}
		return resultList;
	}

	private Map<String, String> exclusionToMap(List<Object> list, Map<String, String> roleMap){
		Map<String, String> resultMap = new HashMap<String, String>();
		
		Map tmpMap = null;
		String rowId = "";
		String roleId = "";
		String roleName = "";
		String excluRoleId = "";
		String excluRoleName = "";
		for (Object object : list) {
			if(object instanceof Map){
				tmpMap = (Map) object;
				rowId = (String) tmpMap.get("rowId");
				roleId = (String)tmpMap.get("roleId");
				roleName = (String)tmpMap.get("roleName");
				excluRoleId = (String)tmpMap.get("excluRoleId");
				excluRoleName = (String)tmpMap.get("excluRoleName");
				resultMap.put(rowId, roleId + "," + excluRoleId);
				if(!roleMap.containsKey(roleId)){
					roleMap.put(roleId, roleName);
				}
				if (!roleMap.containsKey(excluRoleId)) {
					roleMap.put(excluRoleId, excluRoleName);
				}
				roleMap.put((String) tmpMap.get("roleId"), (String) tmpMap.get("roleName"));
			}
		}
		
		return resultMap;
	}
}
